package cn.tinlan.shopcoin.app.mine.order;



import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;

import com.google.gson.reflect.TypeToken;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;
import com.zhouyou.http.EasyHttp;
import com.zhouyou.http.callback.CallClazzProxy;
import com.zhouyou.http.exception.ApiException;
import com.zhouyou.http.subsciber.BaseSubscriber;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import cn.tinlan.shopcoin.R;
import cn.tinlan.shopcoin.Utils.SPUtils;
import cn.tinlan.shopcoin.Utils.ToastUtils;

import cn.tinlan.shopcoin.base.BaseFragment;
import cn.tinlan.shopcoin.base.CustomApiResult;
import cn.tinlan.shopcoin.widget.category.Constants;
import io.reactivex.Observable;

/**
 * Created by Mortimer on 2018/11/27. 10:48
 * 佛祖🙏，永无bug。
 */
public class OrderFragment extends BaseFragment {

    @BindView(R.id.order_refresh)
    SmartRefreshLayout order_refresh;
    @BindView(R.id.order_rv)
    RecyclerView order_rv;

    OrderAdapter orderAdapter;
    List<OrderItemModel> orderList;

    public int orderType = 1;
    private int page = 1;
    @Override
    protected int provideContentViewId() {
        return R.layout.fragment_order;
    }

    @Override
    protected void loadData() {

    }

    @Override
    public void initView(View rootView) {
        super.initView(rootView);

        initRView();
        initSmartRefreshLayout();
    }


    @Override
    public void initData() {
        super.initData();

        page = 1;
        loadOrderData(page);

    }

    private void initSmartRefreshLayout() {
        order_refresh.setRefreshHeader(new ClassicsHeader(getActivity()));
        order_refresh.setRefreshFooter(new ClassicsFooter(getActivity()));
        order_refresh.setEnableScrollContentWhenLoaded(true);//是否在加载完成时滚动列表显示新的内容
        order_refresh.setEnableFooterFollowWhenLoadFinished(true);
        order_refresh.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                page++;
                loadOrderData(page);
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {

                page = 1;
                loadOrderData(page);
            }
        });
    }



    private void initRView() {
        if (orderAdapter == null){
            LinearLayoutManager llm = new LinearLayoutManager(mActivity, LinearLayoutManager.VERTICAL, false);
            order_rv.setLayoutManager(llm);
//            shop_car_rv.addItemDecoration(new DividerItemDecoration(mActivity, DividerItemDecoration.VERTICAL));
            orderAdapter = new OrderAdapter(mActivity,R.layout.view_order_item, R.layout.view_order_head, null);
            order_rv.setAdapter(orderAdapter);
        }else {
            orderAdapter.notifyDataSetChanged();
        }


    }


    private void loadOrderData(final int page1){
        Observable<List<OrderResultModel>> observable = EasyHttp.get(Constants.OrderList)
                .params("user_id", SPUtils.getUserID(mActivity))
                .params("page",""+page1)
                .params("status",orderType+"")
                .execute(new CallClazzProxy<CustomApiResult<List<OrderResultModel>>, List<OrderResultModel>>(new TypeToken<List<OrderResultModel>>() {}.getType()) {
                });

        observable.subscribe(new BaseSubscriber<List<OrderResultModel>>() {
            @Override
            public void onError(ApiException e) {
                if (page > 1){
                    page--;
                }else {
                    page = 1;
                }
                ToastUtils.show("数据请求失败");

            }

            @Override
            public void onNext(List<OrderResultModel> OrderResultModels) {
                super.onNext(OrderResultModels);

                if (orderList == null){
                    orderList = new ArrayList<>();
                }
                List<OrderItemModel> temList = new ArrayList<>();
                for (int i = 0; i<OrderResultModels.size(); i++) {

                    OrderResultModel tempModel = OrderResultModels.get(i);
                    temList.add(new OrderItemModel(true, tempModel.getOrder_sn(),tempModel));
                    List<OrderResultModel.OrderGoodModel> goodModels = tempModel.getGoods();
                    for (int j = 0; j<goodModels.size(); j++) {
                        OrderResultModel.OrderGoodModel goodModel = goodModels.get(j);
                        boolean isLastGood = j == (goodModels.size() - 1);
                        temList.add(new OrderItemModel(new OrderItemModel.OrderItemBean(goodModel,isLastGood,tempModel.getMoney(),goodModels.size()+"")));
                    }

                }

                if (page1 == 1){
                    order_refresh.finishRefresh();
                    if (OrderResultModels.size() < 1) {
                        ToastUtils.show("订单暂无");
                        return;
                    }
                    orderList = temList;
                    orderAdapter.setNewData(temList);

//                    mShopListAdapter.notifyDataSetChanged();
                }else {
                    orderList.addAll(temList);
                    orderAdapter.addData(temList);
                    if (OrderResultModels.size() < 16) {
                        order_refresh.finishLoadMoreWithNoMoreData();  //全部加载完成,没有数据了调用此方法
                    }else {
                        order_refresh.finishLoadMore();      //加载完成
                    }

//
                }

            }
        });



    }
}
